package cn.tedu.order.tcc;

import cn.tedu.order.entity.Order;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
@Component
public class OrderTCCActionImpl implements OrderTCCAction {
    @Autowired
    private OrderMapper orderMapper;

    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long id, Long userId, Long productId, Integer count, BigDecimal money) {
        Order order = new Order(id, userId, productId, count, money, 0);
        // 插入冻结订单
        orderMapper.create(order);
        //第一阶段完成时保存标记
        ResultHolder.setResult(OrderTCCAction.class, ctx.getXid(),"p" );
        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {
        //检查标记是否存在，如果不存在说明之前已将回滚过，不在重复执行回滚
        if (ResultHolder.getResult(OrderTCCAction.class, ctx.getXid())==null){
            return true;
        }
        /*
        ctx上下文对象在向第二阶段传递时，会先转成 json，再从json转回上下文对象，
        其中的整数可以是Integer也可能是Long
         */
        Long orderId = Long.valueOf(ctx.getActionContext("id").toString());

        // 把状态修改成正常状态
        orderMapper.updateStatus(orderId, 1);
        //第二阶段提交完成时，删除标记
        ResultHolder.removeResult(OrderTCCAction.class, ctx.getXid());
        return true;
    }

    @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {
        Long orderId = Long.valueOf(ctx.getActionContext("id").toString());
        // 删除订单
        orderMapper.deleteById(orderId);
        return true;
    }
}
